package cn.pconline.autoclub.web.admin;

import cn.pconline.autoclub.entity.ClubLevel;
import cn.pconline.autoclub.entity.MessageDetail;
import cn.pconline.autoclub.entity.SendMsg;
import cn.pconline.autoclub.entity.Theme;
import cn.pconline.autoclub.service.ClubLevelService;
import cn.pconline.autoclub.service.SendMsgService;
import cn.pconline.autoclub.service.ThemeService;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 发系统消息的相关查询操作，都不走缓存
 *
 * @author 作者 guoqiang
 * @version 2014-6-25
 */
@Controller
@RequestMapping("/admin")
public class SendMsgController {

    @Autowired
    private SendMsgService sendMsgService;
    @Autowired
    private ThemeService themeService;
    @Autowired
    private ClubLevelService clubLevelService;
    private static final Logger log = LoggerFactory.getLogger(SendMsgController.class);

    private void errorMsg(String msg, HttpServletResponse resp) {
        try {
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(
                    new JSONBuilder()
                    .put("statusCode", 300)
                    .put("message", msg)
                    .toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    private void successMsg(String msg, String navTabId, HttpServletResponse resp, String callbackType) {
        try {
            String rs = StringUtils.isEmpty(msg) ? "操作成功" : msg;
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(new JSONBuilder()
                    .put("statusCode", 200)
                    .put("message", rs)
                    .put("navTabId", navTabId)
                    .put("callbackType", callbackType)
                    .toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    /**
     * 查询系统消息列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/message/list")
    public String listSendMsg(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long msgId = env.paramLong("msgId", 0);
        String msg = env.param("msg", "");
        String beginDate = env.param("beginDate", "");
        String endDate = env.param("endDate", "");
        String createBy = env.param("createBy", "");
        int pageNo = env.paramInt("pageNum", 1);
        String orderField = env.param("orderField", "create_at");
        int pageSize = 20;
        Pager<SendMsg> pager = sendMsgService.pageForMsg(msgId, msg, beginDate, endDate, createBy, orderField, pageNo, pageSize);
        req.setAttribute("pager", pager);
        req.setAttribute("msgId", msgId == 0 ? "" : msgId);
        req.setAttribute("msg", msg);
        req.setAttribute("beginDate", beginDate);
        req.setAttribute("endDate", endDate);
        req.setAttribute("createBy", createBy);
        req.setAttribute("orderField", orderField);
        return "admin/system/messageList";
    }

    /**
     * 查询系统消息详情
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/message/detail")
    public String messageDetail(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long msgId = env.paramLong("msgId", 0);
        SendMsg msg = sendMsgService.findMsgFromDb(msgId);
        List<Theme> themes = themeService.listAllThemes();
        List<ClubLevel> clubLevels = clubLevelService.getAllLevels();
        req.setAttribute("themes", themes);
        req.setAttribute("clubLevels", clubLevels);
        req.setAttribute("message", msg);
        req.setAttribute("msgId", msgId);
        return "admin/system/messgeDetail";
    }

    /**
     * 发送系统消息
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/message/create")
    public void create(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long adminId = GeliSession.getCurrentUser().getUserId();
        String content = env.param("content", "");
        int DB_MAX_LENGTH = 400, DB_MAX_LENGTH2 = 1000;
        if (content.length() >= DB_MAX_LENGTH) {
            errorMsg("系统消息内容太长了！", resp);
            return;
        }
        Date sendAt = WebUtils.parseDate(env.param("sendAt"));
        int sendAll = env.paramInt("sendAll", 0);
        String areaAndBrandCombineStr = env.param("areaAndBrandSerialStr", "");
        if (areaAndBrandCombineStr.length() >= DB_MAX_LENGTH2) {
            errorMsg("你选的组合太多了！", resp);
            return;
        }
        boolean success = sendMsgService.createSystemMsg(content, sendAt, sendAll, adminId, areaAndBrandCombineStr);
        if (!success) {
            errorMsg("没有满足条件的人员！", resp);
        } else {
            successMsg("保存成功，将为你创建消息记录，请稍等", "list-message", resp, "closeCurrent");
        }
    }

    /**
     * 修改信息，当消息已发送后，不能修改
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/message/send")
    public void send(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long msgId = env.paramLong("msgId", 0);
        int status = env.paramInt("status", 0);
        SendMsg message = sendMsgService.findMsgFromDb(msgId);
        req.setAttribute("msgId", msgId);
        if (message.getStatus() == SendMsg.SEND_BEIN) {
            sendMsgService.updateStatus(message, status);
            successMsg("发送准备中", "list-message", resp, null);
        } else if (message.getStatus() == SendMsg.SEND_END) {
            sendMsgService.updateStatus(message, status);
            successMsg("重发准备中", "list-message", resp, null);
        } else {
            errorMsg("发送失败", resp);
        }
    }

    /**
     * 查询系统消息列表
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/msgdetail/list")
    public String listMsgdetail(HttpServletRequest req, HttpServletResponse resp) {
        Env env = EnvUtils.getEnv();
        long msgId = env.paramLong("msgId", 0);
        int ERROR＿STATUS = 99;
        Integer status = env.paramInt("status", ERROR＿STATUS);
        if (status == ERROR＿STATUS) {
            status = null;
        }
        int pageNo = env.paramInt("pageNum", 1);
        String orderField = env.param("orderField", "create_at");
        String orderDirection = env.param("orderDirection", "desc");
        int pageSize = env.paramInt("pageSize", 25);
        Pager<MessageDetail> pager = sendMsgService.pageForMsgDetail(msgId, status, orderField, orderDirection, pageNo, pageSize);
        req.setAttribute("pager", pager);
        req.setAttribute("orderField", orderField);
        req.setAttribute("orderDirection", orderDirection);
        req.setAttribute("msgId", msgId == 0 ? "" : msgId);
        req.setAttribute("status", status);
        return "admin/system/msgList";
    }
    
    /**
     * 删除消息
     * @param request
     * @param response
     */
    @RequestMapping(value = "/message/delete.do", method = RequestMethod.POST)
    public void delete(HttpServletRequest request, HttpServletResponse response) {
    	long msgId = WebUtils.paramLong(request, "msgId", 0);
    	SendMsg sendMsg = sendMsgService.findMsgFromDb(msgId);
    	if(sendMsg == null) {
    		errorMsg("此消息不在在", response);
    		return;
    	}
    	
    	try {
    		sendMsgService.remove(sendMsg, msgId);
        	successMsg("删除成功", "list-message", response, null);
    	} catch(Exception exception) {
    		errorMsg("删除失败", response);
    	}
    }
}
